package com.hmyd.hmyd_android.shop;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.JfMallMessageAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfo;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.Info;
import com.hmyd.hmyd_android.dto.Message;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.ui.BasicListActivity;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

/**
 * 站内信
 * 
 * @author wangk
 *
 */
@ContentView(R.layout.activity_jf_mall_message)
public class JfMallMessageActivity extends BasicListActivity {

	private final int GET_JFMALL_MESSAGE_LIST = 1;
	private final int DELETE_JFMALL_ITEM = 2;
	private final int GET_JFMALL_MESSAGE_LOADMORE = 3;
	private final int POST_READED = 4;

	private final int REQUEST_READ_CODE = 101;

	@ViewInject(R.id.messageTitle)
	private RelativeLayout messageTitle;
	@ViewInject(R.id.messageContent)
	private XListView messageContent;
	@ViewInject(R.id.home_title_txt)
	private TextView messageLogo;
	@ViewInject(R.id.home_right)
	private TextView home_right;
	@ViewInject(R.id.optLayout)
	private RelativeLayout optLayout;
	

	private List<String> msgIds;

	private JfMallMessageAdapter messageAdapter;

	private Page<Message> messagePage;

	private List<Message> datas;

	private int edtiPostion;
	
	private int clickcount = 0;
	private long firstClickTime = 0L; // 第一次单击事件
	private long secondClickTime = 0L; // 第二次单击事件

	private int count = 0; // 删除、已读成功计数

	@OnClick({R.id.readAll, R.id.deleteAll })
	public void click(View v) {
		switch (v.getId()) {
		case R.id.readAll: // 全部已读
			msgIds = messageAdapter.getSelectedMessageId();
			if (msgIds != null) {
				for (String id : msgIds) {
					RequestParams params = new RequestParams();
					params.addBodyParameter("messageId", id);
					onRequest(POST_READED, UrlConstant.READED_SHOP_MESSAGE,
							HttpMethod.POST, params);
					for (Message msg : datas) {
						if (id.equals(msg.messageId)) {
							msg.unread = false;
						}
					}
				}
				messageAdapter.notifyDataSetChanged();
			}
			break;
		case R.id.deleteAll: // 删除全部
			msgIds = messageAdapter.getSelectedMessageId();
			if (msgIds != null) {
				for (String id : msgIds) {
					RequestParams params = new RequestParams();
					params.addBodyParameter("messageId", id);
					onRequest(DELETE_JFMALL_ITEM, UrlConstant.DEL_SHOP_MESSAGE,
							HttpMethod.POST, params);
					Message tempmsg = null;
					for (Message msg : datas) {
						if (id.equals(msg.messageId)) {
							tempmsg = msg;
						}
					}
					datas.remove(tempmsg);
				}
				messageAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	public XListView getXList() {
		return messageContent;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onPostSuccess(int postId, String msg) {
		super.onPostFailure(postId, msg);
		Gson gson = new Gson();
		switch (postId) {
		case GET_JFMALL_MESSAGE_LIST:
			Type type = new TypeToken<DtoInfo<Message>>() {
			}.getType();
			DtoInfo<Message> dto = new DtoInfo<Message>();
			dto = gson.fromJson(msg, type);
			messagePage = dto.data;
			datas.clear();
			datas.addAll(messagePage.records);
			messageAdapter.notifyDataSetChanged();
			if (getXList() != null) {
				if (dto.data.hasMore) {
					getXList().setPullLoadEnable(true);
				} else {
					getXList().setPullLoadEnable(false);
				}
			}
			break;
		case DELETE_JFMALL_ITEM:
			Type type3 = new TypeToken<DtoInfoNoPage<Info>>() {
			}.getType();

			DtoInfoNoPage<Info> dto3 = gson.fromJson(msg, type3);
			int suc = dto3.suc;
			if (suc == 1011) {
				count++;
			}
			break;
		case POST_READED:
			Type type4 = new TypeToken<DtoInfoNoPage<Info>>() {
			}.getType();

			DtoInfoNoPage<Info> dto4 = gson.fromJson(msg, type4);
			Info info = dto4.data;
			int suc2 = dto4.suc;
			if (suc2 == 1011) {
				count++;
			}
			break;
		case GET_JFMALL_MESSAGE_LOADMORE:
			Type type2 = new TypeToken<DtoInfo<Message>>() {
			}.getType();
			dto = gson.fromJson(msg, type2);
			messagePage = dto.data;
			datas.addAll(messagePage.records);
			messageAdapter.notifyDataSetChanged();
			if (getXList() != null) {
				if (dto.data.hasMore) {
					getXList().setPullLoadEnable(true);
				} else {
					getXList().setPullLoadEnable(false);
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		super.onPostFailure(postId, msg);

	}

	@Override
	protected void setParams() {
		messageTitle.setOnTouchListener(touch);
		home_right.setText("编辑");
		messageLogo.setText("站内信");
		messagePage = new Page<Message>();
		datas = new ArrayList<Message>();
		messageLogo.setOnClickListener(doubleTouchToTop);
		messageAdapter = new JfMallMessageAdapter(JfMallMessageActivity.this, datas);
		getXList().setPullRefreshEnable(true); // 允许下拉刷新
		getXList().setPullLoadEnable(true);// 允许加载更多
		getXList().setAutoLoadEnable(false);// 禁止自动加载
		getXList().setXListViewListener(this);
		getXList().setAdapter(messageAdapter);
		onRequest(GET_JFMALL_MESSAGE_LIST, UrlConstant.SHOP_MESSAGE,
				HttpMethod.GET, null);
	}

	@OnItemClick({ R.id.messageContent })
	public void itemClick(AdapterView<?> parent, View view, int position,
			long id) {
		edtiPostion = position - 1;
		Message message = datas.get(edtiPostion);
		startActivityForResult(JfMallMessageDetailActivity.getIntent(
				JfMallMessageActivity.this, message), REQUEST_READ_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_READ_CODE && resultCode == RESULT_OK) {
			datas.get(edtiPostion).unread = false;
			messageAdapter.notifyDataSetChanged();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AppBasic.getInstance().finishCurrentActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onRefresh() {
		super.onRefresh();
		onRequest(GET_JFMALL_MESSAGE_LIST, UrlConstant.SHOP_MESSAGE,
				HttpMethod.GET, null);
	}

	@Override
	public void onLoadMore() {
		super.onLoadMore();
		Long lastCursor = null;
		if (datas.size() > 0) {
			lastCursor = datas.get(datas.size() - 1).sendTime;
			RequestParams params = new RequestParams();
			params.addBodyParameter("lastCursor", String.valueOf(lastCursor));
			onRequest(GET_JFMALL_MESSAGE_LOADMORE, UrlConstant.SHOP_MESSAGE,
					HttpMethod.GET, params);
		}
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}
	
	/**
	 * 双加返回屏幕顶端
	 */
	OnClickListener doubleTouchToTop = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			clickcount++;
			if(clickcount==1) {
				firstClickTime = System.currentTimeMillis();
			}
			if(clickcount == 2) {
				secondClickTime = System.currentTimeMillis();
				if(secondClickTime-firstClickTime<1000) {
					getXList().scrollTo(0, 0);
					getXList().smoothScrollToPosition(0);
				}
				clickcount = 0;
				firstClickTime = 0L;
				secondClickTime = 0L;
			}
		}
	};

	@Override
	protected void rightButton() {
		if (!messageAdapter.isShow) {
			home_right.setText("取消");
			messageAdapter.isShow = true;
			messageAdapter.notifyDataSetChanged();
			optLayout.setVisibility(View.VISIBLE);
		} else {
			home_right.setText("编辑");
			messageAdapter.isShow = false;
			messageAdapter.notifyDataSetChanged();
			optLayout.setVisibility(View.GONE);
		}
	}

}
